<template>
  <div class="AddGloudWarehouse">
    <div v-if="state == 'edit'"><h4>编辑云仓</h4></div>
    <div v-else><h4>添加云仓</h4></div>
    <div class="cus-title-1">
      <span>仓库信息</span>
    </div>
    <div class="cus-form">
      <el-form ref="elform" :model="bindForm" :rules="pattern">
        <el-form-item prop="warehouseName" label="仓库名称:">
          <el-col :span="20">
            <el-input v-model="bindForm.warehouseName" placeholder="输入名称" maxlength="20" />
          </el-col>
        </el-form-item>
        <el-form-item label="仓库地址:" required>
          <el-col :span="20">
            <div class="top">
              <el-form-item prop="provinceCode">
                <el-select
                  ref="province"
                  v-model="bindForm.provinceCode"
                  filterable
                  clearable
                  @change="handelProvince"
                >
                  <el-option
                    v-for="(item, index) in pca.province"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="cityCode">
                <el-select
                  v-model="bindForm.cityCode"
                  filterable
                  clearable
                  @change="handelCity"
                >
                  <el-option
                    v-for="(item, index) in pca.forCity"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="areaCode">
                <el-select
                  v-model="bindForm.areaCode"
                  filterable
                  clearable
                  @change="handelArea"
                >
                  <el-option
                    v-for="(item, index) in pca.forArea"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop="detailAddress">
                <!--                <el-input
                  v-model="bindForm.detailAddress"
                  placeholder="详细地址"
                  style="width:400px;"
                />-->
                <el-amap-search-box
                  ref="searchBox"
                  v-model="bindForm.detailAddress"
                  style="border-radius: 5px; border: 1px solid #F3F3F3;height: 36px;"
                  :search-option="searchOption"
                  :on-search-result="onSearchResult"
                />
              </el-form-item>
            </div>
          </el-col>
        </el-form-item>
        <div class="bottom">
          <el-amap
            ref="map"
            vid="amapDemo"
            :amap-manager="amapManager"
            :center="center"
            :zoom="zoom"
            :plugin="plugin"
            :events="events"
            class="amap-demo"
            style="height:500px;"
          >
            <el-amap-marker :position="center" />
          </el-amap>
        </div>
        <el-form-item>
          <el-button
            type="primary"
            style="width:100px;margin-top:100px"
            :loading="butloading"
            @click="handelSubmit"
          >提交</el-button>
          <el-button
            type="primary"
            @click="returnPage"
          >返回上一页</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
/** 添加云仓 */
import { getCityList } from '@/api/auth'
import {
  gloudWarehouseAdd,
  gloudWarehouseEdit
} from '@/api/customAPI/shop/GloudWarehouse'
import VueAMap from 'vue-amap'
const amapManager = new VueAMap.AMapManager()
let Geocoder // 先声明变量，
export default {
  name: 'AddGloudWarehouse',
  data() {
    return {
      butloading: false,
      // 配送区域
      pca: {
        // 省区
        province: [],
        // 需要循环遍历的城区和市区
        city: [],
        area: [],
        // 最后拿到的 城区和市区 select 列表
        forCity: [],
        forArea: []
      },
      // 表单
      baiduMap: '',
      keywordSearch: [],
      location: '',
      state: '',
      bindForm: {
        shopId: localStorage.getItem('shopId'),
        warehouseName: '',
        provinceID: '',
        provinceName: '',
        provinceCode: '',
        cityID: '',
        cityName: '',
        cityCode: '',
        areaID: '',
        areaName: '',
        areaCode: '',
        detailAddress: '',
        latitudeAndLongitude: ['116.404', '39.915']
      },
      pattern: {
        warehouseName: [
          { required: true, message: '请输入仓库名', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'change' },
          { max: 100, message: '限定字符100', trigger: 'change' }
        ],
        areaCode: [
          {
            required: true,
            message: '请选择区/县',
            trigger: ['change', 'blur']
          }
        ],
        cityCode: [
          { required: true, message: '请选择市区', trigger: ['change', 'blur'] }
        ],
        provinceCode: [
          { required: true, message: '请选择省区', trigger: ['change', 'blur'] }
        ]
      },
      amapManager,
      zoom: 18,
      markers: [],
      searchOption: {
        city: '杭州',
        citylimit: false
      },
      center: [120.19, 30.26],
      events: {
        init: (o) => {
          o.getCity((result) => {
            console.log(result)
          })
        },
        moveend: () => {},
        zoomchange: () => {},
        click: (e) => {
          this.center = [e.lnglat.lng, e.lnglat.lat]
          Geocoder.getAddress(this.center, function(status, result) { // 根据坐标获取位置
            if (status === 'complete' && result.info === 'OK') {
              this.bindForm.detailAddress = result.regeocode.formattedAddress
              this.$refs.searchBox.keyword = this.bindForm.detailAddress
            }
          })
        }
      },
      plugin: [
        {
          pName: 'Geocoder', // 使用AMap.Geocoder插件
          events: {
            init(o) {
              Geocoder = o // o 则是AMap.Geocoder的实例 对外部的Geocoder变量进行赋值，在任何地方就都可以使用了
              // self.center 具体坐标 （数组格式） ，function 回调函数
              o.getAddress(this.center, function(status, result) {
                if (status === 'complete' && result.info === 'OK') {
                  // result.regeocode.formattedAddress就是具体位置
                  this.bindForm.detailAddress = result.regeocode.formattedAddress
                  // 对搜索组件的input进行赋值
                  this.$refs.searchBox.keyword = this.bindForm.detailAddress
                }
              })
            }
          }
        },
        {
          showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
          pName: 'Geolocation', // AMap-Geolocation 定位插件
          events: {
            init(o) {
              // getCurrentPosition 获取当前位置的方法
              // 注意 虽然进页面就会调用这个方法，但是data()中center要有默认值，不然会报错
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  const lng = result.position.lng
                  const lat = result.position.lat
                  this.center = [lng, lat]
                  this.loaded = true
                  this.zoom = 18
                  this.$nextTick()
                }
              })
            }
          }
        }
      ]
    }
  },
  created() {
    const param = this.$dd(this.$route.query.p)
    this.state = param.state
  },
  mounted() {
    this.getProvince()
  },
  activated() {
    this.getProvince()
  },
  methods: {
    loadding() {
      console.log(this.$route.query)
      const param = this.$dd(this.$route.query.p)
      if (param.state === 'edit') {
        this.bindForm.warehouseName = param.row.name
        this.bindForm.provinceCode = param.row.provinceId
        this.bindForm.cityCode = param.row.cityId
        this.bindForm.areaCode = param.row.villageId
        this.bindForm.detailAddress = param.row.addressDetail
        this.bindForm.areaName = param.row.village
        this.bindForm.cityName = param.row.city
        this.bindForm.provinceName = param.row.province
        this.bindForm.latitudeAndLongitude = [
          param.row.lng,
          param.row.lat
        ]
        this.center = [param.row.lng, param.row.lat]
        this.$nextTick(() => {
          this.$refs.searchBox.keyword = this.bindForm.detailAddress
          this.provinceCity()
        })
      }
    },
    getProvince() {
      getCityList()
        .then(result => {
          this.pca.province = []
          this.pca.city = []
          this.pca.area = []
          result.data.data.forEach(inf => {
            this.pca.province.push(inf.province)
            inf.cityRegion.forEach(reg => {
              this.pca.city.push(reg.city) // 拿市区
              reg.village.forEach(vil => {
                this.pca.area.push(vil) // 拿城区
              })
            })
          })
          if (this.state === 'edit') {
            this.loadding()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    /** 修改时初始化 */
    provinceCity() {
      const param = this.$dd(this.$route.query.p)
      const provinceInfo = this.$XEUtils.find(this.pca.province, item => item.code === param.row.provinceId)
      this.pca.city.forEach(inf => {
        if (inf.pid === provinceInfo.id) {
          this.pca.forCity.push(inf)
        }
      })
      const cityInfo = this.$XEUtils.find(this.pca.city, item => item.code === param.row.cityId)
      this.pca.area.forEach(inf => {
        if (inf.pid === cityInfo.id) {
          this.pca.forArea.push(inf)
        }
      })
    },
    returnPage() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },
    /** 提交/修改 */
    handelSubmit() {
      const params = this.$dd(this.$route.query.p)
      this.butloading = true
      this.$refs.elform.validate(v => {
        if (v) {
          if (
            this.state === 'add'
          ) {
            const data = this.$XEUtils.clone(this.bindForm, true)
            data.provinceID = this.bindForm.provinceCode
            data.cityID = this.bindForm.cityCode
            data.areaID = this.bindForm.areaCode
            if (data.cityName === data.provinceName) {
              data.cityName = '市辖区'
            }
            delete data.provinceCode
            delete data.cityCode
            delete data.areaCode

            gloudWarehouseAdd(data)
              .then(result => {
                this.$message.success('添加成功')
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          } else if (this.state === 'edit') {
            this.bindForm.id = params.row.id
            const data = this.$XEUtils.clone(this.bindForm, true)
            data.provinceID = this.bindForm.provinceCode
            data.cityID = this.bindForm.cityCode
            data.areaID = this.bindForm.areaCode
            if (data.cityName === data.provinceName) {
              data.cityName = '市辖区'
            }
            delete data.provinceCode
            delete data.cityCode
            delete data.areaCode
            gloudWarehouseEdit(data)
              .then(result => {
                this.$message.success('编辑成功')
                this.butloading = false
                this.$store.dispatch('tagsView/delView', this.$route)
                this.$router.go(-1)
              })
              .catch(() => {
                this.butloading = false
              })
          }
        } else {
          this.butloading = false
        }
      })
    },
    /** 区 */
    handelArea(v) {
      /* console.log(v, '区id')
      this.bindForm.areaName = this.pca.area.find(inf => {
        return inf.id === v
      }).name
      this.addressName()*/
      if (v) {
        this.bindForm.areaName = this.pca.area.find(inf => {
          return inf.code === v
        }).name
        this.bindForm.areaId = this.pca.area.find(inf => {
          return inf.code === v
        }).code
      }
    },
    /** 市 */
    handelCity(v) {
      if (v) {
        this.pca.forArea = []
        this.bindForm.areaName = ''
        this.bindForm.areaId = ''
        this.bindForm.areaCode = null
        const cityInfo = this.$XEUtils.find(this.pca.city, item => item.code === v)
        this.pca.area.forEach(inf => {
          if (inf.pid === cityInfo.id) {
            this.pca.forArea.push(inf)
          }
        })
        this.bindForm.cityName = this.pca.city.find(inf => {
          return inf.code === v
        }).name
        this.bindForm.cityId = this.pca.city.find(inf => {
          return inf.code === v
        }).code
      }
      /* this.pca.forArea = []
      this.pca.area.forEach(inf => {
        if (inf.pid === v) {
          this.pca.forArea.push(inf)
        }
      })
      this.bindForm.cityName = this.pca.city.find(inf => {
        return inf.id === v
      }).name
      this.addressName()*/
    },
    /** 省 */
    handelProvince(v) {
      this.pca.forCity = []
      this.pca.forArea = []
      this.location = ''
      this.bindForm.cityID = ''
      this.bindForm.areaID = ''
      this.bindForm.cityCode = null
      this.bindForm.areaCode = null
      if (v) {
        const provinceInfo = this.$XEUtils.find(this.pca.province, item => item.code === v)
        this.pca.city.forEach(inf => {
          if (inf.pid === provinceInfo.id) {
            this.pca.forCity.push(inf)
          }
        })
        /* this.pca.city.forEach(inf => {
        if (inf.pid === v) {
          this.pca.forCity.push(inf)
        }
      })*/
        this.bindForm.detailAddress = ''
        this.bindForm.cityName = ''
        this.bindForm.areaName = ''
        this.bindForm.detailAddress = ''
        this.bindForm.provinceName = this.pca.province.find(inf => {
          return inf.code === v
        }).name
        this.bindForm.provinceID = this.pca.province.find(inf => {
          return inf.code === v
        }).id
        this.bindForm.provinceCode = this.pca.province.find(inf => {
          return inf.code === v
        }).code
      }
    },
    /** 点击搜索后触发的事件 */
    onSearchResult(pois) {
      if (pois.length > 0) {
        pois.forEach(item => {
          if (this.$refs.searchBox.keyword == item.name) {
            this.center = [item.lng, item.lat]
          } else {
            // 这边类似模糊查询 会返回一个数组，我就直接取第一个值了。
            this.center = [pois[0].lng, pois[0].lat]
          }
        })
      }
      this.bindForm.detailAddress = this.$refs.searchBox.keyword
      this.bindForm.latitudeAndLongitude = this.center
    }
  }
}
</script>

<style lang="scss" scoped>
.AddGloudWarehouse {
  padding: 50px 100px;
  .cus-title-1 {
    width: 100%;
    height: 50px;
    line-height: 50px;
    border-radius: 5px;
    background: #f3f3f3;
    padding: 0px 20px;
    margin-bottom: 40px;
  }
  .cus-form {
    padding: 0px 20px;
    ::v-deep.el-form {
      margin-top: 40px;
      .el-form-item__label {
        width: 100px;
        text-align: start;
      }
      .el-form-item__error {
        margin-left: 100px;
      }
      .el-form-item {
        padding-left: 20px;
        .el-input {
          width: 200px;
        }
        ::v-deep.el-select {
          width: 800px;
          margin-right: 30px;
        }
        .top {
          padding-bottom: 30px;
          display: flex;
          .el-form-item {
            margin: 0;
            padding: 0;
          }
          .el-form-item__error {
            margin-left: 0px;
          }
        }
      }
    }
  }
  .bottom {
    .baidu-map {
      width: 100%;
      height: 600px;
    }
  }
}
</style>
